package cn.com.io.day20151215;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

/**
 * Created by Administrator on 2015/12/16.
 */
public class CharsetTransform {
    public static void main(String[] args) throws CharacterCodingException {
        Charset charset =Charset.forName(System.getProperty("file.encoding"));//创建简体中文对应的Charset
        CharsetEncoder encoder = charset.newEncoder();//获取charset对象对应的编码器
        CharsetDecoder decoder = charset.newDecoder();//获取charset对象对应的解码器
        CharBuffer charBuffer = CharBuffer.allocate(8);//创建一个CharBuffer对象
        charBuffer.put('开');
        charBuffer.put('源');
        charBuffer.put('中');
        charBuffer.put('国');
        charBuffer.flip();
        ByteBuffer byteBuffer = encoder.encode(charBuffer); //将CharBuffer的字符序列转换成字节序列
        //循环访问byteBuffer中的每个字节
        System.out.println(byteBuffer.limit());
        for(int i=0;i<byteBuffer.limit();i++){
            System.out.print(byteBuffer.get(i) + "    ");
        }
        System.out.println("\n"+decoder.decode(byteBuffer));//将ByteBuffer的数据解码成字符序列
    }
}
